<!-- 分配角色页面 -->
<template>
  <el-dialog
    v-dialogDrag
    title="角色列表"
    :visible.sync="isDialogAssignRoleShow"
    width="50%"
    :before-close="closeDialog"
  >
    <el-table
      ref="roleTable"
      v-loading="isLoading"
      height="400"
      :data="roleData"
      label-position="left"
      @selection-change="handleSelectionChange"
      @row-click="openRole"
    >
      <el-table-column
        align="center"
        type="selection"
        width="48"
      />
      <el-table-column sortable align="center" label="序号">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        sortable
        align="center"
        prop="name"
        label="角色名"
      />
      <el-table-column
        sortable
        align="center"
        prop="code"
        label="角色代码"
      />
      <el-table-column
        align="center"
        prop="remarke"
        label="备注"
      />
    </el-table>
    <el-pagination
      :page-size="paginationData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="paginationData.total"
      :current-page.sync="paginationData.pageCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <span slot="footer" class="dialog-footer">
      <el-button id="btnCancel" @click="closeDialog">取 消</el-button>
      <el-button id="btnOK" type="primary" @click="assignRole">确 定</el-button>
      <!-- :disabled= "this.$store.state.user.judge" -->
    </span>
  </el-dialog>
</template>
<script>
import {
  commonQuery
} from '@/api/right/role'
import { modifyWithNewRole } from '@/api/right/user'

export default {
  name: 'DialogAssignRole',
  props: {
    isDialogAssignRoleShow: {
      require: true,
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      queryLoading: false,
      // 用户信息
      userData: [],
      // 用户信息参数
      userQuery: {
        id: '',
        code: '',
        roleId: '',
        tenantId: '',
        orgId: '',
        companyId: '',
        createdBy: '',
        creater: '',
        createdTime: '',
        updatedBy: '',
        modifier: ''
      },
      // 角色信息
      roleData: [],
      // 当前页选中的角色信息
      currentRoleDataSelection: [],
      // 被选中的角色信息表 用于跨页
      roleDataSelectionForm: [],
      // 被选中的角色信息
      roleDataSelection: [],
      // 获取角色信息的参数
      roleQuery: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      // 分页信息
      paginationData: {
        // 当前页面序号，默认为1
        pageCount: 1,
        // 每页数据数
        pageSize: 10,
        // 总共数据数
        total: 0,
        // 总页面数
        pages: null
      },
      // 是否处于加载状态
      isLoading: false
    }
  },
  mounted() {
    this.$nextTick(function() {
      /**
       * 获取用户信息,改为接口对应格式,获取角色信息
       */
      this.$on('getUserSelection', (userDataSelection) => {
        userDataSelection.map(item => {
          const user = {}
          for (let key in this.userQuery) {
            if (item[key]) {
              user[key] = item[key]
            }
          }
          user.modifier = this.$store.getters.name
          this.userData.push(user)
        })
        this.getRole()
      })
    })
  },
  methods: {
    /**
      * 获取角色信息
      */
    async getRole() {
      try {
        this.isLoading = true
        let res = await commonQuery(this.roleQuery)
        if (res) {
          const { total, data } = res
          this.roleQuery.total = parseInt(total)
          this.paginationData.total = parseInt(total)
          this.roleData = data

          // 若本页有数据被选中，则选中
          this.$nextTick(() => {
            if (this.roleDataSelectionForm[this.paginationData.pageCount - 1]) {
              const rows = this.roleDataSelectionForm[this.paginationData.pageCount - 1]
              rows.forEach(row => {
                this.roleData.map(item => {
                  if (item.id === row.id) {
                    this.$refs.roleTable.toggleRowSelection(item, true)
                  }
                })
              })
            }
          })
        }
      } catch {
        this.$message.error('网络错误')
      } finally {
        this.isLoading = false
      }
    },
    /**
     * 分配角色
     */
    assignRole() {
      this.$confirm('分配角色将覆盖已有角色，请慎重操作')
        .then(res => {
          const userVOS = []
          // 获取选中role的Id数组
          const roleList = this.roleDataSelection.map(item => { return { id: item.id } })
          if (roleList.length === 0) {
            this.$message.error('至少选择一个角色')
            return
          }
          // 将选中的用户数据添加上role的Id数组
          this.userData.map(user => {
            userVOS.push({ ...user, roleList })
          })
          modifyWithNewRole(userVOS)
            .then(res => {
              if (res) {
                this.$message.success('角色分配成功')
                this.$emit('operateUserSuccess')
                this.closeDialog()
              } else {
                this.$message.error('角色分配失败')
                this.closeDialog()
              }
            })
            .catch(() => {
              this.$message.error('网络错误')
              this.visible = false
            })
        })
        .catch(() => {})
    },
    /**
     * 跳转至role
     */
    openRole(row) {
      this.$router.push({ path: '/role' })
    },
    /**
     * 更改被选中数据的数组
     * @param {*} val 被选中的数据
     */
    handleSelectionChange(val) {
      // 更新选中的数据
      val.forEach(item => {
        if (!this.currentRoleDataSelection.includes(item)) {
          this.roleDataSelection.push(item)
        }
      })
      this.currentRoleDataSelection.forEach(item => {
        if (!val.includes(item)) {
          const index = this.roleDataSelection.findIndex(v => v === item)
          this.roleDataSelection.splice(index, 1)
        }
      })

      this.currentRoleDataSelection = val
    },
    /**
     * 关闭弹窗
     */
    closeDialog() {
      this.userData = []
      this.$emit('closeDialog')
    },
    /**
     * 更改页面尺寸时重新获取数据
     * @param {*} val
     */
    handleSizeChange(val) {
      this.paginationData.pageSize = val
      this.roleQuery.pageSize = val
      this.roleDataSelectionForm = []
      this.roleDataSelection = []
      this.currentRoleDataSelection = []
      this.getRole()
    },
    /**
     * 当前页面发生变化时重新获取数据
     * @param {*} val
     */
    handleCurrentChange(val) {
      this.roleDataSelectionForm[this.roleQuery.pageNum - 1] = this.currentRoleDataSelection
      // 添加离去页的数据，防止遗漏
      this.roleDataSelection.push(...this.currentRoleDataSelection)
      // 删除到达页的数据，防止重复
      if (this.roleDataSelectionForm[val - 1]) {
        this.roleDataSelectionForm[val - 1].forEach(item => {
          const index = this.roleDataSelection.findIndex(v => v === item)
          this.roleDataSelection.splice(index, 1)
        })
      }

      this.roleQuery.pageNum = val
      this.getRole()
    }
  }
}
</script>
